﻿using System;
using System.Windows.Forms;
using Finance.TodoSoft;
using TodoSoft.Reporting;

namespace Finance.Views
{
	public partial class DateTimeIntervalControl : UserControl
	{
		public DateTimeIntervalControl()
		{
			InitializeComponent();
		}

		public event EventHandler PeriodChanged;

		private void OnButtonDayClick(object sender, EventArgs e)
		{
			var now = DateTime.Now.Date;
			dateTimePickerStart.Value = now;
			dateTimePickerEnd.Value = now;

			PeriodChanged.InvokeIfNotNull(this, e);
		}

		private void OnButtonMonthClick(object sender, EventArgs e)
		{
			var now = DateTime.Now;
			dateTimePickerEnd.Value = new DateTime(now.Year, now.Month, now.Day).AddDays(1).AddTicks(-1);
			dateTimePickerStart.Value = new DateTime(now.Year,now.Month, 1);

			PeriodChanged.InvokeIfNotNull(this, e);
		}

		private void OnButtonYearClick(object sender, EventArgs e)
		{
			var now = DateTime.Now;
			dateTimePickerEnd.Value = new DateTime(now.Year, now.Month, now.Day).AddDays(1).AddTicks(-1);
			dateTimePickerStart.Value = now.AddDays(1 - now.Day).AddMonths(1-now.Month);

			PeriodChanged.InvokeIfNotNull(this, e);
		}

		private void OnButtonAllClick(object sender, EventArgs e)
		{
			DateTimeInterval = new DateTimeInterval(Parameter.MinValue, Parameter.MaxValue);

			PeriodChanged.InvokeIfNotNull(this, e);
		}

		private void OnButtonUpdateClick(object sender, EventArgs e)
		{
			PeriodChanged.InvokeIfNotNull(this, e);
		}

		private DateTimeInterval _dateTimeInterval;

		public DateTimeInterval DateTimeInterval
		{
			get
			{
				_dateTimeInterval.Start = dateTimePickerStart.Value;
				_dateTimeInterval.End = dateTimePickerEnd.Value;
				return _dateTimeInterval;
			}
			set
			{
				_dateTimeInterval = value;
				if (_dateTimeInterval.Start <= _dateTimeInterval.End)
				{
					dateTimePickerEnd.Value = _dateTimeInterval.End;
					dateTimePickerStart.Value = _dateTimeInterval.Start;
				}
				else
				{
					dateTimePickerStart.Value = _dateTimeInterval.End;
					dateTimePickerEnd.Value = _dateTimeInterval.Start; 
				}
			}
		}

		public PeriodReportParameter Parameter { get; set; }
	}
}